use serde_json::*;
use std::{fs, io::Read, collections::HashMap};
use serde::{Serialize, Deserialize};
use tauri::{plugin::Plugin, Invoke, Runtime, AppHandle, Window, PageLoadPayload};

#[derive(Serialize, Deserialize, Debug)]
struct I18n {
    locale: String,
    #[serde(flatten)]
    extra: HashMap<String, Value>,
}


#[tauri::command]
fn file_read(path: String) -> String {
    let mut contents = String::new();
    let mut file = fs::File::open(path).unwrap();
    file.read_to_string(&mut contents).unwrap();
    return contents;
}

#[tauri::command]
fn initialize() {}

pub struct I18nLoader<R: Runtime> {
    invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>,
}

impl<R: Runtime> I18nLoader<R> {
    pub fn new() -> Self {
        Self {
            invoke_handler: Box::new(tauri::generate_handler![
                initialize,
                file_read
           ])
        }
    }
}

impl<R: Runtime> Plugin<R> for I18nLoader<R> {
    fn name(&self) -> &'static str {
        "i18n"
    }

    fn initialize(&mut self, _app: &AppHandle<R>, _config: Value) -> tauri::plugin::Result<()> {
        Ok(())
    }

    fn initialization_script(&self) -> Option<String> {
        None
    }

    fn on_page_load(&mut self, _window: Window<R>, _payload: PageLoadPayload) {}

    fn extend_api(&mut self, message: Invoke<R>) {
        (self.invoke_handler)(message)
    }
}